package com.xhg.controller;


import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;

import com.jfinal.plugin.activerecord.Record;
import com.xhg.common.Constants;
import com.xhg.common.auth.UserToken;
import com.xhg.model.RolePower;
import com.xhg.model.User;
import com.xhg.util.image.Captcha;
import com.xhg.util.safe.MD5Util;

/**
 * 开放访问无拦截
 * @author wjw
 */
public class MainController extends BaseController{
	
	private RolePower rpService=RolePower.dao;
	
	/**
	 * 登陆页面
	 */
    public void index() {
        render("login.jsp");
    }
    /**
     * 登陆action
     * Login
     */
    public void login() {
    	User user_session=getSessionAttr(Constants.SESSION_USER_KEY);//获取session中的用户
    	if(user_session==null){
    		User obj=getModel(User.class);
			if (obj == null || obj.getStr("userName") == null|| obj.getStr("password") == null) {
				setAttr("msg","用户名或密码不能为空!");
				render("login.jsp");
				return;
			}
    		obj.set("password",MD5Util.getEncrypt(obj.getStr("password")));//对用户密码加密
    		Subject subject = SecurityUtils.getSubject();
			UserToken userToken=new UserToken(obj,true);
			try {
				subject.login(userToken);//登陆授权认证
				if(subject.isAuthenticated()){
					user_session=getSessionAttr(Constants.SESSION_USER_KEY);//获取session中的用户
					//通过用户对象查询对应角色权限集合
					List<Record> rpList=rpService.queryAllPowersByRoleIds(user_session);
					setSessionAttr(Constants.SESSION_USER_POWER, rpList);//将用户菜单权限添加到session中
					render("index.jsp");//返回成功页面
					return;
				}
			} catch (UnknownAccountException e) {
				setAttr("msg","用户名或密码错误!");
			} catch (LockedAccountException e) {
				setAttr("msg","用户未激活或被锁定，请与管理员联系!");
			} catch (ExcessiveAttemptsException e) {
				setAttr("msg","错误次数过多!");
			} catch (AuthenticationException e) {
				setAttr("msg","未知的登录错误!");
			}
			render("login.jsp");
			return;
    	}
    	render("index.jsp");//返回成功页面
    }
    /**
     * 退出系统
     * @return
     */
	public void exit() {
		HttpServletResponse response=getResponse();
		setSessionAttr(Constants.SESSION_USER_KEY,null);//清除session
		cleanCache(response);//清除缓存
		renderJson(true);
	}
	/**
	 * 清除缓存
	 */
	private void cleanCache(HttpServletResponse response){
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
	}
	/**
	 * 生成验证码，以流返回图像
	 */
	public void captcha(){
		Captcha.getCaptcha(getResponse(),getSession());
		renderNull();
	}
	/**
	 * 校验验证码
	 */
	public void validateCaptcha(){
		String captcha=getRequest().getParameter("captcha");
    	String captcha_session= (String) getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
    	renderJson(captcha.equals(captcha_session));//相同验证通过
	}
/*==========================================================================================*/
    /**
     * app登陆action
     * @return text
     */
    public void loginApp() {
    	User user_session=getSessionAttr(Constants.SESSION_USER_KEY);//获取session中的用户
    	if(user_session==null){
    		User obj=getModel(User.class);
			if (obj == null || obj.getStr("userName") == null|| obj.getStr("password") == null) {
				render("用户名或密码不能为空!");
				return;
			}
    		obj.set("password",MD5Util.getEncrypt(obj.getStr("password")));//对用户密码加密
    		Subject subject = SecurityUtils.getSubject();
			UserToken userToken=new UserToken(obj,true);
			try {
				subject.login(userToken);//登陆授权认证
				if(subject.isAuthenticated()){
					user_session=getSessionAttr(Constants.SESSION_USER_KEY);//获取session中的用户
					//通过用户对象查询对应角色权限集合
					List<Record> rpList=rpService.queryAllPowersByRoleIds(user_session);
					setSessionAttr(Constants.SESSION_USER_POWER, rpList);//将用户菜单权限添加到session中
					renderText("succeed");//返回成功页面
					return;
				}
			} catch (UnknownAccountException e) {
				renderText("用户名或密码错误!");
			} catch (LockedAccountException e) {
				renderText("用户未激活或被锁定，请与管理员联系!");
			} catch (ExcessiveAttemptsException e) {
				renderText("错误次数过多!");
			} catch (AuthenticationException e) {
				renderText("未知的登录错误!");
			}
			renderText("登陆失败!");
			return;
    	}
    	renderText("succeed");//返回成功页面
    }
}